import router from '@/router/index'
import {useAuthStore} from "@/stores/auth";
import {useNavbarStore} from "@/stores/navbar";
import {getAuthorStatus} from "@/api/author";

router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore();
    const navbarStore = useNavbarStore();
    navbarStore.setActiveIndex(to.path);

    // 基础路由处理：如果用户已登录且访问login/register页面，则跳转至home
    if ((to.path === '/login' || to.path === '/register') && authStore.getToken()) {
        next({path: '/home'});
    } else if (to.path === '/author/register') {
        // 特殊处理：作者注册页面，若已登录则检查作者状态
        if (authStore.getToken()) {
            const {data} = await getAuthorStatus();
            if (data === null) {
                next();
            } else {
                next({path: '/author/book_list'});
            }
        } else {
            next({path: '/login'});
        }
    } else {
        // 其他情况：如果用户未登录且访问非login/register页面，则跳转至login
        if (!authStore.getToken() && to.path !== '/login' && to.path !== '/register') {
            next({path: '/login'});
        } else {
            next(); // 用户已登录或访问的是login/register页面时，直接继续导航
        }
    }
});
